<template>
  <div class="cyber-dashboard">
    <!-- 背景装饰元素 -->
    <div class="cyber-grid"></div>
    <div class="cyber-scanline"></div>

    <div class="dashboard-header">
      <div class="header-glow"></div>
      <h1 class="dashboard-title">
        <span class="title-text">
          <a :href="`/clusters`" class="task-id">返回</a>
          聚类任务控制台
        </span>
        <span class="title-pulse"></span>
      </h1>
      <div class="app-info">
        <span class="app-id">APP ID: {{ appId }}</span>
        <div class="status-indicator">
          <div class="pulse-dot" :class="{'active': embeddingStatus === 'processed'}"></div>
          <span>已就绪</span>
        </div>
      </div>
    </div>

    <!-- 文本嵌入区域 -->
    <div class="cyber-card embedding-section">
      <div class="card-glow"></div>
      <div class="section-header">
        <h2 class="section-title">
          <span class="icon">⚡</span>
          文本嵌入
        </h2>
        <div class="cyber-line"></div>
      </div>
      <div class="embedding-controls">
        <div class="control-grid">
          <div class="cyber-input-group">
            <label class="control-label">嵌入模型:</label>
            <select v-model="selectedModel" class="cyber-select" :disabled="embeddingStatus === 'processing'">
              <option value="text-embedding-v4">text-embedding-v4</option>
              <option value="text-embedding-ada-002">text-embedding-ada-002</option>
              <option value="all-MiniLM-L6-v2">all-MiniLM-L6-v2</option>
            </select>
          </div>
          <div class="cyber-input-group">
            <label class="control-label">维度:</label>
            <input v-model="embeddingDimension" type="number" class="cyber-input" min="128" max="1024"/>
          </div>
        </div>
        <div class="action-row">
          <button
              @click="handleEmbedding"
              class="cyber-button primary"
              :disabled="embeddingStatus === 'processing'"
              :class="{ 'processing': embeddingStatus === 'processing' }"
          >
            <span class="button-content">
              <span class="button-glow"></span>
              {{ embeddingStatus === 'processing' ? '正在嵌入...' : (embeddingStatus === 'processed' ? '重新嵌入' : '开始嵌入') }}
            </span>
          </button>
          <div class="status-display">
            <div class="status-light" :class="statusClass"></div>
            <span class="status-text">状态: {{ embeddingStatus === 'processing' ? '正在嵌入...' : (embeddingStatus === 'processed' ? '已嵌入' : '未嵌入') }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 词云图区域 -->
    <div class="cyber-card wordcloud-section">
      <div class="card-glow"></div>
      <div class="section-header">
        <h2 class="section-title">
          <span class="icon">☁️</span>
          词云分析
        </h2>
        <button
            @click="toggleWordCloud"
            class="cyber-button secondary"
        >
          {{ showWordCloud ? '隐藏词云图' : '展示词云图' }}
        </button>
      </div>

      <!-- 投影仪动画容器 -->
      <div class="projector-container" v-if="showWordCloud">
        <div class="projector-beam" :class="{'active': showWordCloud}"></div>
        <div class="wordcloud-display" :class="{'projecting': showWordCloud}">
          <div class="wordcloud-canvas" ref="wordcloudCanvas"></div>
          <div class="loading-overlay" v-if="wordCloudLoading">
            <div class="loading-spinner"></div>
            <span class="loading-text">词云生成中...</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 词问题显示弹窗 -->
    <div v-if="showWordQuestionsModal" class="cyber-modal-overlay" @click="closeWordQuestionsModal">
      <div class="cyber-modal" @click.stop>
        <div class="modal-header">
          <h3>QUESTIONS CONTAINING "{{ selectedWord.toUpperCase() }}"</h3>
          <button @click="closeWordQuestionsModal" class="cyber-close-button">
            <span>×</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="questions-scroll">
            <div v-for="(question, index) in wordQuestions" :key="index" class="question-item">
              <div class="question-index">{{ (index + 1).toString().padStart(2, '0') }}</div>
              <div class="question-text">{{ question }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 任务列表区域 -->
    <div class="cyber-card tasks-section">
      <div class="card-glow"></div>
      <div class="section-header">
        <h2 class="section-title">
          <span class="icon">🔧</span>
          聚类任务管理
        </h2>
        <button @click="showCreateTaskModal = true" class="cyber-button primary">
          + 创建任务
        </button>
      </div>

      <!-- 任务创建弹窗 -->
      <div v-if="showCreateTaskModal" class="cyber-modal-overlay" @click="closeCreateTaskModal">
        <div class="cyber-modal" @click.stop>
          <div class="modal-header">
            <h3>创建聚类任务</h3>
            <button @click="closeCreateTaskModal" class="cyber-close-button">
              <span>×</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="cyber-form">
              <div class="form-group">
                <label class="form-label">任务描述</label>
                <input v-model="newTaskDescription" type="text" class="cyber-input" placeholder="ENTER TASK DESCRIPTION"/>
              </div>
              <div class="form-group">
                <label class="form-label">聚类数</label>
                <input v-model="newTaskClusters" type="number" class="cyber-input" min="2" max="100" value="10"/>
              </div>
              <div class="form-group">
                <label class="form-label">聚类算法</label>
                <select v-model="newTaskModel" class="cyber-select">
                  <option value="kmeans">K-MEANS</option>
                  <option value="dbscan">DBSCAN</option>
                  <option value="hierarchical">HIERARCHICAL</option>
                </select>
              </div>
              <button @click="createTask" class="cyber-button primary confirm-button">
                任务初始化
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 任务列表 -->
      <div class="tasks-container">
        <div class="tasks-toolbar">
          <div class="selection-control">
            <label class="cyber-checkbox">
              <input
                  type="checkbox"
                  v-model="selectAll"
                  @change="toggleSelectAll"
                  class="checkbox-input"
              />
              <span class="checkmark"></span>
              <span class="checkbox-label">全选</span>
            </label>
          </div>
          <button
              @click="confirmDeleteSelected"
              :disabled="selectedTasks.length === 0"
              class="cyber-button danger"
          >
            批量删除
          </button>
        </div>

        <div class="tasks-grid">
          <div
              v-for="task in tasks"
              :key="task.task_id"
              class="task-card"
              :class="{ 'selected': selectedTasks.includes(task.task_id) }"
          >
            <div class="task-selector">
              <label class="cyber-checkbox small">
                <input
                    type="checkbox"
                    :value="task.task_id"
                    v-model="selectedTasks"
                    class="checkbox-input"
                />
                <span class="checkmark"></span>
              </label>
            </div>
            <div class="task-content">
              <div class="task-header">
                <a :href="`/clusters/${appId}/${task.task_id}`" class="task-id">任务ID: {{ task.task_id }}</a>
                <span class="task-model">{{ task.model?.toUpperCase() || 'K-MEANS' }}</span>
              </div>
              <div class="task-description">{{ task.description || '暂无描述' }}</div>
              <div class="task-meta">
                <span class="cluster-count">聚类数: {{ task.k_cluster }}</span>
                <span class="task-status">状态: 已就绪</span>
              </div>
            </div>
            <div class="task-actions">
              <button @click="deleteTask(task.task_id)" class="cyber-button danger small">
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Notification ref="notification"></Notification>
  </div>
</template>

<script setup>
import Notification from "@/components/Notification.vue";
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import * as d3 from 'd3'
import cloud from 'd3-cloud'

// 路由参数
const route = useRoute()
const appId = route.params.app_id

// 响应式数据
const selectedModel = ref('text-embedding-v4')
const embeddingDimension = ref(512)
const embeddingStatus = ref('false')
const showWordCloud = ref(false)
const wordCloudData = ref([])
const wordCloudLoading = ref(false)
const showWordQuestionsModal = ref(false)
const selectedWord = ref('')
const wordQuestions = ref([])
const tasks = ref([])
const showCreateTaskModal = ref(false)
const newTaskDescription = ref('')
const newTaskClusters = ref(10)
const newTaskModel = ref('kmeans')
const selectedTasks = ref([])
const selectAll = ref(false)
const notification = ref(null)
const wordcloudCanvas = ref(null)

// 计算属性
const statusClass = computed(() => {
  return embeddingStatus.value === 'processing' ? 'processing' :
      embeddingStatus.value === 'processed' ? 'success' : 'idle'
})

// 获取嵌入状态
const fetchEmbeddingStatus = async () => {
  try {
    const response = await fetch(`http://localhost:5000/apps/embed/status?app_id=${appId}`)
    const data = await response.json()
    embeddingStatus.value = data.status
  } catch (error) {
    notification.value.showNotificationMessage(error, 'error')
  }
}

// 处理文本嵌入
const handleEmbedding = async () => {
  if (embeddingStatus.value === 'processing') return

  try {
    embeddingStatus.value = 'processing'
    const response = await fetch('http://localhost:5000/apps/embed', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        app_id: appId,
        model: selectedModel.value,
        dimension: embeddingDimension.value
      })
    })
    const data = await response.json()

    if (data.message === 'queued' || data.message === 'processing') {
      // 开始轮询状态
      const pollStatus = setInterval(async () => {
        const statusResponse = await fetch(`http://localhost:5000/apps/embed/status?app_id=${appId}`)
        const statusData = await statusResponse.json()
        embeddingStatus.value = statusData.status
        if (statusData.status !== 'processing') {
          clearInterval(pollStatus)
        }
      }, 2000)
    }
  } catch (error) {
    embeddingStatus.value = 'false'
    notification.value.showNotificationMessage(error, 'error')
  }
}

// 切换词云显示
const toggleWordCloud = async () => {
  if (!showWordCloud.value) {
    showWordCloud.value = true
    wordCloudLoading.value = true

    try {
      const response = await fetch('http://localhost:5000/word_cloud/app_word_cloud', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({app_id: appId})
      })
      const data = await response.json()

      if (data.error && typeof data.error === 'string') {
        console.log(data)
        notification.value.showNotificationMessage(data.error, 'error')
        showWordCloud.value = false
        wordCloudLoading.value = false
        return
      }

      // 转换数据格式
      const wordData = Object.entries(data).map(([word, frequency]) => ({
        text: word,
        size: Math.max(20, frequency * 3), // 基础大小 + 频率权重
        frequency: frequency
      })).sort((a, b) => b.frequency - a.frequency).slice(0, 50) // 取前100个高频词

      wordCloudData.value = wordData

      // 等待DOM更新后绘制词云
      await nextTick()
      drawWordCloud(wordData)

    } catch (error) {
      console.log(error)
      notification.value.showNotificationMessage(error, 'error')
      showWordCloud.value = false
      wordCloudLoading.value = false
    }
  } else {
    showWordCloud.value = false
    wordCloudData.value = []
    // 清理词云
    if (wordcloudCanvas.value) {
      d3.select(wordcloudCanvas.value).selectAll("*").remove()
    }
  }
}

// 绘制词云
const drawWordCloud = (words) => {
  if (!wordcloudCanvas.value) return

  // 清理现有内容
  d3.select(wordcloudCanvas.value).selectAll("*").remove()

  const width = wordcloudCanvas.value.clientWidth
  const height = 400

  // 创建SVG
  const svg = d3.select(wordcloudCanvas.value)
      .append("svg")
      .attr("width", width)
      .attr("height", height)

  // 创建容器组
  const g = svg.append("g")
      .attr("transform", `translate(${width/2},${height/2})`)

  // 设置颜色比例尺
  const colorScale = d3.scaleSequential()
      .domain([0, words.length - 1])
      .interpolator(d3.interpolateCool)

  // 创建词云布局
  const layout = cloud()
      .size([width, height])
      .words(words)
      .padding(3)
      .rotate(() => 0)
      .font("Arial")
      .fontSize(d => d.size)
      .on("end", draw)

  layout.start()

  function draw(calculatedWords) {
    wordCloudLoading.value = false

    const word = g.selectAll("text")
        .data(calculatedWords)
        .enter().append("text")
        .style("font-size", d => `${d.size}px`)
        .style("font-family", "Arial")
        .style("fill", (d, i) => colorScale(i))
        .style("cursor", "pointer")
        .style("opacity", 0)
        .attr("text-anchor", "middle")
        .attr("transform", d => `translate(${d.x},${d.y}) rotate(${d.rotate})`)
        .text(d => d.text)
        .on("click", function(event, d) {
          showWordQuestions(d.text)
        })
        .on("mouseover", function() {
          d3.select(this)
              .transition()
              .duration(200)
              .style("filter", "url(#glow)")
              .style("font-size", function() {
                const currentSize = parseFloat(d3.select(this).style("font-size"))
                return `${currentSize * 1.2}px`
              })
        })
        .on("mouseout", function() {
          d3.select(this)
              .transition()
              .duration(200)
              .style("filter", "none")
              .style("font-size", function() {
                const currentSize = parseFloat(d3.select(this).style("font-size"))
                return `${currentSize / 1.2}px`
              })
        })

    // 添加发光滤镜
    const defs = svg.append("defs")
    const filter = defs.append("filter")
        .attr("id", "glow")
    filter.append("feGaussianBlur")
        .attr("stdDeviation", "3.5")
        .attr("result", "coloredBlur")
    const feMerge = filter.append("feMerge")
    feMerge.append("feMergeNode")
        .attr("in", "coloredBlur")
    feMerge.append("feMergeNode")
        .attr("in", "SourceGraphic")

    // 动画显示
    word.transition()
        .duration(1000)
        .delay((d, i) => i * 20)
        .style("opacity", 1)
  }
}

// 显示单词相关问题
const showWordQuestions = async (word) => {
  try {
    const response = await fetch('http://localhost:5000/word_cloud/questions_for_word', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        app_id: appId,
        word: word
      })
    })
    const data = await response.json()

    selectedWord.value = word
    wordQuestions.value = data.questions || data
    showWordQuestionsModal.value = true

  } catch (error) {
    notification.value.showNotificationMessage(error, 'error')
  }
}

// 关闭单词问题弹窗
const closeWordQuestionsModal = () => {
  showWordQuestionsModal.value = false
  selectedWord.value = ''
  wordQuestions.value = []
}

// 获取任务列表
const fetchTasks = async () => {
  try {
    const response = await fetch('http://localhost:5000/tasks/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({app_id: appId})
    })
    const data = await response.json()

    if (Array.isArray(data)) {
      tasks.value = data
    }
  } catch (error) {
    notification.value.showNotificationMessage(error, 'error')
  }
}

// 创建任务
const createTask = async () => {
  if (embeddingStatus.value !== 'processed') {
    notification.value.showNotificationMessage('请先完成文本嵌入！！！', 'error')
    return
  }
  if (!newTaskDescription.value.trim()) {
    notification.value.showNotificationMessage('请输入任务描述！！！', 'error')
    return
  }

  try {
    const response = await fetch('http://localhost:5000/tasks/create', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        app_id: appId,
        k_cluster: parseInt(newTaskClusters.value),
        model: newTaskModel.value,
        description: newTaskDescription.value
      })
    })
    const data = await response.json()

    if (data.error) {
      notification.value.showNotificationMessage(data.error, 'error')
      return
    }

    closeCreateTaskModal()
    await fetchTasks()

    notification.value.showNotificationMessage('任务创建成功！', 'success')
  } catch (error) {
    notification.value.showNotificationMessage(`创建任务失败:${error}`, 'error')
  }
}

// 关闭创建任务弹窗
const closeCreateTaskModal = () => {
  showCreateTaskModal.value = false
  newTaskDescription.value = ''
  newTaskClusters.value = 10
  newTaskModel.value = 'kmeans'
}

// 删除任务
const deleteTask = async (taskId) => {
  if (!confirm('确定要删除这个任务吗？此操作不可撤销。')) {
    return
  }

  try {
    const response = await fetch('http://localhost:5000/tasks/delete', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        app_id: appId,
        task_ids: [taskId]
      })
    })
    const data = await response.json()

    if (data.message === 'success') {
      await fetchTasks()
      notification.value.showNotificationMessage('任务删除成功！', 'success')
    } else {
      notification.value.showNotificationMessage(data.error || '删除任务失败', 'error')
    }
  } catch (error) {
    notification.value.showNotificationMessage('删除任务失败: ' + error, 'error')
  }
}

// 确认删除选中任务
const confirmDeleteSelected = () => {
  if (selectedTasks.value.length === 0) return

  if (!confirm(`确定要删除选中的 ${selectedTasks.value.length} 个任务吗？此操作不可撤销。`)) {
    return
  }

  deleteSelectedTasks()
}

// 删除选中任务
const deleteSelectedTasks = async () => {
  try {
    const response = await fetch('http://localhost:5000/tasks/delete', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        app_id: appId,
        task_ids: selectedTasks.value
      })
    })
    const data = await response.json()

    if (data.message === 'success') {
      await fetchTasks()
      selectedTasks.value = []
      selectAll.value = false
      notification.value.showNotificationMessage('批量删除成功！', 'success')
    } else {
      notification.value.showNotificationMessage(data.error || '删除任务失败', 'error')
    }
  } catch (error) {
    notification.value.showNotificationMessage('删除任务失败: ' + error, 'error')
  }
}

// 全选/取消全选
const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedTasks.value = tasks.value.map(task => task.task_id)
  } else {
    selectedTasks.value = []
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  await fetchEmbeddingStatus()
  await fetchTasks()
})
</script>

<style src="@/assets/styles/task-list.css"></style>